//
//  M4LoadingAlertView.swift
//  M4
//
//  Created by YuChuang on 2024/8/8.
//

import UIKit
import SDWebImage

class M4LoadingAlertView: UIView {
    
    lazy var loadingImage: UIImageView = {
        let img = UIImageView()
        img.contentMode = .scaleAspectFit
        let path = Bundle.main.path(forResource:"M4Loading", ofType:"gif") ?? ""
        let url = URL(fileURLWithPath: path)
        do {
            let data = try Data(contentsOf: url)
            img.image = UIImage.sd_image(withGIFData: data)
        } catch {
            print("Error converting GIF path to Data: \(error)")
        }
        return img
    }()

    override init(frame: CGRect) {
        super.init(frame: .zero)
        self.frame = CGRect(x: 0, y: 0, width: M4ScreenWidth, height: M4ScreenHeight)
        self.tag = 1111
        self.backgroundColor = COLOR_000000.withAlphaComponent(0.6)
        let bgView = UIView()
        bgView.backgroundColor = .white
        bgView.layer.cornerRadius = 5
        self.addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.height.equalTo(80)
        }
        bgView.addSubview(loadingImage)
        loadingImage.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.height.equalTo(60)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func M4LoadingAlertShow() {
        var open: Bool = false
        for dtView in UIApplication.shared.keyWindow?.subviews ?? [] {
            if dtView.tag == 1111 {
//                open = true
                break
            }
        }
        if open == true {return}
        UIApplication.shared.keyWindow?.addSubview(self)
        self.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
        UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut) {
            self.alpha = 1
            self.transform = CGAffineTransform.identity
        }
    }
    
}
